<template>
  <div class="app-container">
    <el-form ref="formRef" :disabled="!editAble" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="盘点编号" prop="inventoryCode">
            <code-input
              v-if="editAble"
              v-model="form.inventoryCode"
              code="INVENTORY_CODE"
              :disabled="!!form.id"
              placeholder="请输入盘点编号"
            />
            <div v-else class="form-text">{{ form.inventoryCode }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="盘点主题" prop="inventoryName">
            <el-input v-if="editAble" v-model="form.inventoryName" placeholder="请输入盘点主题" />
            <el-tooltip v-else effect="dark" :content="form.inventoryName">
              <div class="form-text">{{ form.inventoryName }}</div>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <SearchTool
          v-if="editAble"
          :disabled='operationTitle.indexOf("编辑")>-1'
          :code="{
            factory: 'factory',
            workshop: 'workSection',
            line: 'pdcLine',
            section: 'processSection',
          }"
          :titles="{
            factory: '工厂',
            workshop: '工段',
            line: '产线',
            section: '工艺段',
          }"
          :layout="true"
          :span="6"
          v-model:factory="form.factory"
          v-model:workshop="form.workSection"
          v-model:line="form.pdcLine"
          v-model:section="form.processSection"
          @lineChange="toolChange"
          @sectionChange="toolChange"
        ></SearchTool>
        <el-col v-if="!editAble" :span="6">
          <el-form-item label="工厂" prop="factory">
            <div class="form-text">{{ form.factoryName }}</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!editAble" :span="6">
          <el-form-item label="工段" prop="workSection">
            <div class="form-text">{{ form.workShopName }}</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!editAble" :span="6">
          <el-form-item label="产线" prop="pdcLine">
            <div class="form-text">{{ form.lineName }}</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!editAble" :span="6">
          <el-form-item label="工艺段" prop="processSection">
            <div class="form-text">{{ form.sectionName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="线边仓" prop="storehouseName">
            <StoreSelect
              v-if="editAble"
              v-model="form.storehouseCode"
              v-model:name="form.storehouseName"
              :line="form.pdcLine"
              :section="form.processSection"
              placeholder="请选择线边仓"
              @change="storeChange"
            ></StoreSelect>
            <div v-else class="form-text">{{ form.storehouseName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="盘点日期" prop="inventoryDate">
            <el-date-picker
              v-if="editAble"
              v-model="form.inventoryDate"
              clearable
              range-separator="至"
              type="daterange"
              value-format="YYYY-MM-DD"
            />
            <el-tooltip v-else effect="dark" :content="form.inventoryDate">
              <div class="form-text">
                {{ form.inventoryDate ? form.inventoryDate.join("至") : "" }}
              </div>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-if="editAble"
              v-model="form.remark"
              type="textarea"
              :maxlength="200"
              show-word-limit
              placeholder="请输入内容"
            />
            <div v-else class="form-text">{{ form.remark }}</div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- v-hasPermi="['warehouse:InventoryDetail:list']" -->
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="盘点明细" name="first">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          label-width="100px"
          class="form-search"
        >
          <el-form-item label="物料/产品编号" prop="matCode">
            <el-input
              v-model="queryParams.matCode"
              placeholder="请输入物料/产品编号"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="物料/产品名称" prop="matName">
            <el-input
              v-model="queryParams.matName"
              placeholder="请输入物料/产品名称"
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item label="批次号" prop="batchNo">
            <el-input
              v-model="queryParams.batchNo"
              placeholder="请输入批次号"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="类型" prop="matType">
            <el-tree-select
              v-model="queryParams.matType"
              :data="matTypes"
              :check-on-click-node="true"
              node-key="code"
              highlight-current
              filterable
              check-strictly
              :expand-on-click-node="false"
              :props="{ label: 'name', children: 'children' }"
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" @click="handleQuery">查询</el-button>
            <el-button icon="refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-form ref="tableForm" :model="inventoryDetailList" label-width="0">
          <el-table
            v-loading="detailLoad"
            :data="inventoryDetailList"
            :row-class-name="rowIndexMethod"
            border
            maxHeight="400"
            cell-class-name="table-form-item"
            ref="whStorehouseInDetail"
          >
            <el-table-column label="序号" align="center" prop="index" width="80" />
            <el-table-column label="库位" show-overflow-tooltip prop="binCode"></el-table-column>
            <el-table-column
              label="物料/产品编码"
              show-overflow-tooltip
              prop="matCode"
            ></el-table-column>
            <el-table-column
              label="物料/产品名称"
              show-overflow-tooltip
              prop="matName"
            ></el-table-column>
            <el-table-column
              label="类型"
              show-overflow-tooltip
              prop="matTypeName"
            ></el-table-column>
            <el-table-column
              label="单位"
              show-overflow-tooltip
              prop="packageUnit"
            ></el-table-column>
            <el-table-column label="批次号" show-overflow-tooltip prop="batchNo"></el-table-column>
            <el-table-column label="当前库存" show-overflow-tooltip prop="num"></el-table-column>
            <el-table-column
              label="盘点库存"
              :show-overflow-tooltip="!editAble"
              prop="inventoryNum"
            >
              <template v-if="editAble" #header>
                <span style="color: red">*</span>
                <span>盘点库存</span>
              </template>
              <template v-if="editAble" #default="scope">
                <el-form-item
                  label=""
                  :prop="`[${scope.$index}].inventoryNum`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入数量',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input-number
                    v-model="scope.row.inventoryNum"
                    @change="handleInputChange($event, scope, 'inventoryNum')"
                    controls-position="right"
                    :min="0"
                  ></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="偏差量" show-overflow-tooltip prop="inventoryOffset">
              <template #default="scope">
                <div
                  :class="{
                    redText: getOffsetNum(scope.row.inventoryNum, scope.row.num) != 0,
                  }"
                >
                  {{ getOffsetNum(scope.row.inventoryNum, scope.row.num) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="偏差原因"
              :show-overflow-tooltip="!editAble"
              prop="inventoryOffsetReason"
            >
              <template v-if="editAble" #header>
                <!-- <span style="color: red">*</span> -->
                <span>偏差原因</span>
              </template>
              <template v-if="editAble" #default="scope">
                <el-form-item label="" :prop="`[${scope.$index}].inventoryOffsetReason`">
                  <el-input
                    v-if="editAble"
                    v-model="scope.row.inventoryOffsetReason"
                    @change="handleInputChange($event, scope, 'inventoryOffsetReason')"
                    placeholder="请输入偏差原因"
                  />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup name="InventoryDetail">
import { getInventory, addInventory, listDetail, queryMat } from "@/api/warehouse/inventory";
import { getFactoryTree } from "@/api/system/dept";
import Decimal from "decimal.js";
import { nextTick, ref, useAttrs, getCurrentInstance, reactive, toRefs, onMounted } from "vue";
import { queryMatTypeTree } from "@/api/base/material/MatTypeApi";

const attrs = useAttrs();
const { proxy } = getCurrentInstance();
const activeName = ref("first");
const matTypes = ref([]);
const refData = reactive({
  // 表单参数
  form: {},
  queryParams: {
    batchNo: "",
    matName: "",
    matCode: "",
    matTypeName: "",
  },
  // 表单校验
  rules: {
    inventoryCode: [{ required: true, message: "盘点编号不能为空", trigger: "blur" }],
    inventoryName: [{ required: true, message: "盘点主题不能为空", trigger: "blur" }],
    factory: [{ required: true, message: "工厂不能为空", trigger: "blur" }],
    workSection: [{ required: true, message: "工段不能为空", trigger: "blur" }],
    pdcLine: [{ required: true, message: "产线不能为空", trigger: "blur" }],
    storehouseName: [{ required: true, message: "线边仓不能为空", trigger: "blur" }],
    inventoryDate: [{ required: true, message: "盘点日期不能为空", trigger: "blur" }],

    status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
  },
});
const { form, rules, queryParams } = toRefs(refData);
const emit = defineEmits(["close", "setActions", "setIsActionTop"]);
const inventoryDetailList = ref([]);
const operationTitle = ref("");
const detailLoad = ref(false);
const formRef = ref("formRef");
const tableForm = ref("tableForm");
const editAble = ref(false);
const actions = ref([]);
const factoryOptions = ref([]);
const allTableData = ref([]);
function getFactorys() {
  getFactoryTree().then((res) => {
    factoryOptions.value = res.data;
  });
}
getFactorys();

/** 搜索按钮操作 */
function handleQuery() {
  filterSubTable();
}
function getMatType() {
  queryMatTypeTree().then((res) => {
    // formatTree(res.data)
    matTypes.value = res.data;
  });
}
getMatType();
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  filterSubTable();
}

function filterSubTable() {
  const result = [];
  allTableData.value.forEach((el) => {
    if (
      ((queryParams.value.matCode && el.matCode === queryParams.value.matCode) ||
        !queryParams.value.matCode) &&
      ((queryParams.value.matName && el.matName.includes(queryParams.value.matName)) ||
        !queryParams.value.matName) &&
      ((queryParams.value.batchNo && el.batchNo === queryParams.value.batchNo) ||
        !queryParams.value.batchNo) &&
      ((queryParams.value.matType && el.type === queryParams.value.matType) ||
        !queryParams.value.matType)
    ) {
      result.push(el);
    }
  });
  inventoryDetailList.value = result;
}

function handleInputChange(val, scope, field) {
  allTableData.value[scope.$index][field] = val;
  if (field === "inventoryNum") {
    allTableData.value[scope.$index].inventoryOffset = getOffsetNum(val, scope.row.num);
  }
}

// 取消按钮
function cancel() {
  emit("close");
}
function getOffsetNum(num1, num2) {
  if (num1 === undefined || num1 === null || num1 === "") return "";
  return new Decimal(num1).minus(new Decimal(num2));
}
// 表单重置
function reset() {
  form.value = {
    inventoryCode: null,
    inventoryName: null,
    storehouseCode: null,
    storehouseName: null,
    inventoryDate: null,
    inventoryDoneDate: null,
    inventoryUserName: null,
    factory: null,
    workSection: null,
    pdcLine: null,
    processSection: null,
    remark: null,
  };
  formRef.value.resetFields();
  inventoryDetailList.value = [];
  allTableData.value = [];
}

function toolChange() {
  form.value.storehouseName = "";
  form.value.storehouseCode = "";
  form.value.whInventoryDetailList = [];
  inventoryDetailList.value = [];
  allTableData.value = [];
}

/** 修改按钮操作 */
function getInventoryDetail(id) {
  getInventory(id).then((response) => {
    form.value = response.data;
    form.value.inventoryDate = form.value.inventoryDate ? form.value.inventoryDate.split("至") : [];
    // response.data.whInventoryDetailList.forEach((el) => {
    //   el.type = el.matType;
    // });
    //   inventoryDetailList.value = response.data.whInventoryDetailList;
    //   getMatList(form.value)
    // if (proxy.checkPermi(["warehouse:InventoryDetail:list"])) {
      getSubDetail(form.value.inventoryCode);
    // }
  });
}

function getSubDetail(inventoryCode) {
  listDetail({ pageSize: 10000, pageNum: 1, inventoryCode }).then((res) => {
    res.rows.forEach((el) => {
      el.num = el.stockNum;
      el.inventoryOffset = getOffsetNum(el.inventoryNum, el.stockNum);
    });
    allTableData.value = res.rows;
    inventoryDetailList.value = res.rows;
  });
}

function storeChange(val) {
  getMatList(val);
}

function getMatList({ storehouseCode }) {
  detailLoad.value = true;
  //   if (storehouseCode !== form.value.storehouseCode) {
  queryMat({ storehouseCode })
    .then((res) => {
      res.data.forEach((el) => {
        el.stockNum = el.num;
        el.type = el.matType;
      });
      allTableData.value = res.data;
      inventoryDetailList.value = res.data;
      detailLoad.value = false;
    })
    .catch(() => {
      detailLoad.value = false;
    });
  //   }
}

/** 提交按钮 */
function submitForm(type) {
  formRef.value.validate((valid) => {
    if (valid) {
      resetQuery();
      nextTick(() => {
        if (allTableData.value && allTableData.value.length) {
          tableForm.value.validate((result) => {
            if (result) {
              if (type === 1) {
                proxy.$modal
                  .confirm(
                    "盘点完成，将根据实际“盘点库存”更新库存记录。是否确认更新？",
                    "确认更新库存"
                  )
                  .then(() => {
                    form.value.submitType = type;
                    form.value.whInventoryDetailList = allTableData.value;

                    confirmForm();
                  });
              } else {
                form.value.submitType = type;
                form.value.whInventoryDetailList = allTableData.value;
                confirmForm();
              }
            }
          });
        } else {
          if (type === 1) {
            proxy.$modal.msgError("请添加物料数据");
            return;
          }
          form.value.submitType = type;
          form.value.whInventoryDetailList = allTableData.value;
          confirmForm();
        }
      });
    }
  });
}

function confirmForm() {
  const params = JSON.parse(JSON.stringify(form.value));
  params.inventoryDate = params.inventoryDate.join("至");
  addInventory(params).then(() => {
    proxy.$modal.msgSuccess("提交成功");
    cancel();
  });
}

/** 物料入仓明细序号 */
function rowIndexMethod({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

onMounted(() => {
  reset();
  const { data, title } = attrs;
  operationTitle.value = title;

  if (title === "添加盘点" || title === "编辑盘点") {
    editAble.value = true;
    actions.value = [
      {
        text: "取 消",
        theme: "",
        handle: () => {
          cancel();
        },
      },
      {
        text: "暂 存",
        theme: "primary",
        handle: () => {
          submitForm(0);
        },
        loading: false,
      },
      {
        text: "盘点完成",
        theme: "primary",
        handle: () => {
          submitForm(1);
        },
        loading: false,
      },
    ];
  } else if (title === "盘点详情") {
    editAble.value = false;
    actions.value = [];
  }
  emit("setActions", actions.value);
  let newDate = proxy.parseTime(new Date(), "{y}-{m}-{d}");
  form.value.inventoryDate = [newDate, newDate];

  if (data) {
    getInventoryDetail(data.id);
  }
});
</script>

<style lang="scss" scoped>
.redText {
  color: #f00 !important;
}
</style>
